﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using ASBCC.Database.Entity;
using SourceCode.Workflow.Client;
using ASBCC.Database.Service;

namespace ASBCC.Workflow.K2Manager
{
    public class AskForMoreActionHandler : ActionHandlerBase
    {
        #region Constructor

        private string _ccUser;
        protected string CcUser { get { return _ccUser; } set { _ccUser = value; } }


        public AskForMoreActionHandler(SerializableDictionary dataFields, K2AppForm appForm, K2WorkItem workItem, K2ActionInfo actionInfo, string comment, K2AuditDestination auditDestination, List<K2User> outputDestinationUsers,string ccUser) :
            base(dataFields, appForm, workItem, actionInfo, comment, auditDestination, outputDestinationUsers)
        {
            _ccUser = ccUser;
        }

        #endregion

        #region Override Methods
        /// <summary>
        /// 执行流程动作
        /// AskForMore动作不涉及K2
        /// </summary>
        protected override void ExcuteAction()
        {
        }

        protected override void BuildMyActivity()
        {
            K2DataHelper.SuspendMyActivities(WorkItem.ProcInstId);
            CreateNewMyActivityList();
        }

        /// <summary>
        /// AskForMore动作时,重载图章生成方法,不需要生成图章
        /// </summary>
        protected override void BuildProcessStamp()
        {
        }

        protected override string GetActionType()
        {
            return K2ActionType.AskForMore;
        }

        protected override void SendMail()
        {
            string actionType = GetActionType();
            string ApplicationNameEn = FlowProcess.ProcDisplayEn;
            string ApplicationNameCn = FlowProcess.ProcDisplayCn;

            Flow_ProcessMailConfigTableEntity mailConfig = K2DataHelper.GetProcessMailConfig(WorkItem.ProcName, WorkItem.ActivityName, actionType);
            if (mailConfig == null) return;

            EZVisitApplicationTableEntity entity = EZVisitApplicationManager.SelectByKeys(AppForm.FormId);
            if (entity == null) return;

            // 通知Applicant/Creator
            int toApplicantTemplate = mailConfig.ToApplicantTemplate ?? 0;
            if (toApplicantTemplate > 0 && NewMyActivityList != null && NewMyActivityList.Count > 0)
            {
                MyActivityTableEntity myActivity = NewMyActivityList[0];

                EmployeeTableEntity creatorInfo = null;

                if (myActivity.OwnerID.HasValue && myActivity.OwnerID.Value > 0)
                {
                    creatorInfo = K2DataHelper.GetUserInfoById(myActivity.OwnerID.Value);
                }

                string auditUser = (AppForm.DelegateFrom.UserId <= 0 || AppForm.DelegateFrom.UserId == AppForm.CurrentUser.UserId) ?
                    AppForm.CurrentUser.UserEn : string.Format("{0}({1})", AppForm.CurrentUser.UserEn, AppForm.DelegateFrom.UserEn);

                if (CheckMailApplicantRule(creatorInfo))
                {
                    string[] mailAddressArr = new string[] { creatorInfo.Email };

                    string[] ccAddresses = new string[2];

                    List<string> ccAddressesList = new List<string>();


                    EmployeeTableEntity ccUserInfo = null;

                    //要抄送的人不为空的话
                    if (string.Compare(string.Empty, CcUser, true) != 0 && string.Compare("0", CcUser, true) != 0)
                    {
                        ccUserInfo = K2DataHelper.GetUserInfoById(Int32.Parse(CcUser));

                        ccAddressesList.Add(ccUserInfo.Email);
                    }

                    // Send mail to the assistant when the requester was asked for more.
                    if (myActivity.OwnerID.Value == entity.RequesterID && entity.AssistantID != null && entity.AssistantID.Value!=0)
                    {
                        EmployeeTableEntity assistantInfo = K2DataHelper.GetUserInfoById(entity.AssistantID.Value);

                        
                        if (CheckMailApplicantRule(assistantInfo))
                        {
                            ccAddressesList.Add(assistantInfo.Email);
                        }

                    }

                    if (ccAddressesList.Count >= 2)
                    {
                        ccAddresses[0] = ccAddressesList[0];
                        ccAddresses[1] = ccAddressesList[1];
                    }
                    else if (ccAddressesList.Count == 1)
                    {
                        ccAddresses[0] = ccAddressesList[0];
                    }

                    NameValueCollection collection = new NameValueCollection();
                    collection["{EnglishName}"] = creatorInfo.NameCN;
                    collection["{ChineseName}"] = creatorInfo.NameChinese;
                    if (!entity.EZVisitReqNoIsNull())
                        collection["{SerialNumber}"] = entity.EZVisitReqNo;
                    else
                        collection["{SerialNumber}"] = AppForm.ApplicationNo;

                    collection["{AuditUser}"] = auditUser;
                    collection["{AuditTime}"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    collection["{Comments}"] = Comment;
                    collection["{FormURL}"] = DataFields[K2Consts.DataField_Key_FormURL].ToString();

                    NameValueCollection titleCollection = new NameValueCollection();
                    if (!entity.EZVisitReqNoIsNull())
                        titleCollection["{SerialNumber}"] = "EZVisit No：" + entity.EZVisitReqNo;
                    else
                        titleCollection["{SerialNumber}"] = AppForm.ApplicationNo;
                    MailService.MailSender(mailAddressArr, toApplicantTemplate, collection, titleCollection, ccAddresses);
                }
            }
        }

        #endregion

        #region Help Methods
        private MyActivityTableEntity LoadAskForMoreToUserActivity()
        {
            string activityName = AuditDestination.ActivityDestinationList[0].ActivityName;
            int ownerId = AuditDestination.ActivityDestinationList[0].UserArr[0];
            K2User owner = K2DataHelper.GetK2UserById(ownerId);
            MyActivityTableEntity myActivity = new MyActivityTableEntity();
            myActivity.ApplicantID = AppForm.Applicant.UserId;
            myActivity.ApplicantEn = AppForm.Applicant.UserEn;
            myActivity.ApplicantCn = AppForm.Applicant.UserCn;
            myActivity.ApplicationNo = AppForm.ApplicationNo;
            myActivity.ArrvialDate = DateTime.Now;
            myActivity.CreatedDate = DateTime.Now;
            myActivity.CreatorID = AppForm.Creator.UserId;
            myActivity.CreatorEn = AppForm.Creator.UserEn;
            myActivity.CreatorCn = AppForm.Creator.UserCn;
            myActivity.OwnerID = owner.UserId;
            myActivity.OwnerEn = owner.UserEn;
            myActivity.OwnerCn = owner.UserCn;
            myActivity.DutyDate = GetDutyDate(activityName);
            myActivity.EnableBatchAction = false;
            myActivity.FormID = AppForm.FormId;
            myActivity.FormStatus = AppForm.FutureFormStatus;
            myActivity.FormURL = this.GetFormURL();
            myActivity.TargetActivityName = activityName;

            //UnSure
            myActivity.K2ActInstDestID = null;
            myActivity.K2ActivityName = WorkItem.ActivityName;
            myActivity.K2Destination = string.Empty;
            myActivity.K2Folio = AppForm.Folio;
            myActivity.K2ProcInstID = WorkItem.ProcInstId;
            myActivity.K2SerianNumber = string.Empty;

            myActivity.ModifiedDate = DateTime.Now;
            myActivity.MyActivityID = Guid.NewGuid();
            myActivity.ProcName = WorkItem.ProcName;
            myActivity.SourceActionType = ActionInfo.ActionType;
            myActivity.Status = (int)MyActivityStatus.Normal;
            myActivity.Title = AppForm.Title;
            myActivity.ActionRecordID = ActionRecordID;
            return myActivity;
        }

        private void CreateNewMyActivityList()
        {
            NewMyActivityList = new List<MyActivityTableEntity>();
            MyActivityTableEntity entity = LoadAskForMoreToUserActivity();
            NewMyActivityList.Add(entity);
            if (OutputDestinationUsers != null)
            {
                OutputDestinationUsers.Add(new K2User(entity.OwnerID ?? 0, entity.OwnerEn, entity.OwnerCn));
            }
            int delegateTo = GetAccountOfDelegateTo(entity.OwnerID.Value);
            if (delegateTo > 0 && delegateTo != entity.OwnerID.Value)
            {
                MyActivityTableEntity copy = K2Helper.CloneMyActivity(entity);
                copy.MyActivityID = Guid.NewGuid();
                copy.DelegateFromID = entity.OwnerID;
                copy.DelegateFromEn = entity.OwnerEn;
                copy.DelegateFromCn = entity.OwnerCn;

                K2User delegateToUser = K2DataHelper.GetK2UserById(delegateTo);
                if (delegateToUser != null)
                {
                    copy.OwnerID = delegateToUser.UserId;
                    copy.OwnerEn = delegateToUser.UserEn;
                    copy.OwnerCn = delegateToUser.UserCn;
                }
                NewMyActivityList.Add(copy);
                if (OutputDestinationUsers != null)
                {
                    OutputDestinationUsers.Add(new K2User(copy.OwnerID ?? 0, copy.OwnerEn, copy.OwnerCn));
                }
            }
            K2DataHelper.CreateNewMyActivityList(NewMyActivityList);
        }
        #endregion
    }
}
